#include "ThreadPool.h"
ThreadPool::ThreadPool(size_t threadNum,size_t queSize)
:_threadNum(threadNum)
,_queSize(queSize)
,_threads()
,_taskQueue(_queSize)
,_isExit(false){}


ThreadPool::~ThreadPool(){

}
//线程池的开始与结束
void ThreadPool::start(){
    for(size_t idx = 0; idx != _threadNum; ++ idx){
        _threads.push_back(thread(&ThreadPool::doTask,this));
    }
}
void ThreadPool::stop(){
    //只要任务队列不为空，主线程的_isExit就不设置它为ture
    while(!_taskQueue.empty()){
        //主线程放弃CPU控制权，防止CPU空转
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    //线程池退出来了，任务队列为空
    _isExit = true;
    //唤醒可能在_notEmpty上面睡眠的变量
    _taskQueue.wakeup();
    //回收线程对象
    for(auto &th : _threads){
        th.join();
    }
}

void ThreadPool::addTask(Task && taskcb){
     if(taskcb){
        _taskQueue.push(std::move(taskcb));
     }
}

Task ThreadPool::getTask(){
    return _taskQueue.pop();
}

void ThreadPool::doTask(){
    while(!_isExit){
        Task taskcb = getTask();
        if(taskcb){
            taskcb();
        }
        else{
            cout <<"nullptr == ptask" << endl;
        }
    }
}

